const logger = require("../utils/logger")
const mysqlUtil = require("../utils/mysqlUtil")
const commonModule = require('./common')
const moment = require('moment')
const util = require("../utils/util")

module.exports = {

    // 合同审批
    hetongShenpi: async (io, socket, params, callback) => {
        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        logger.debug('hetong shenpi', params)

        let auditorsObj = {}
        for (let i = 0; i != params.auditors.length; i++) {
            auditorsObj['auditor' + i] = { uid: params.auditors[i].uid, stepName: params.auditors[i].stepName, sta: 0 }
        }

        try {
            let res = await mysqlUtil.execute('SELECT name FROM tb_user WHERE uid = ? LIMIT 1', [uid])
            if (res.length == 0) return callback({code: -1, message: '玩家不存在'})
            let name = res[0].name

            // 编号自动生成 查询今年已经有多少申请了
            res = await mysqlUtil.execute('SELECT COUNT(1) cnt FROM tb_user_hetong_shenpi WHERE createTime > ?', [moment().startOf('year').valueOf()])
            let year = new Date().getFullYear()
            let cnt = res[0].cnt
            let bianhao = ''
            if (cnt < 10) {
                bianhao = year + '00' + cnt
            } else if (cnt < 100) {
                bianhao = year  + '0' + cnt
            } else {
                bianhao = year + '' + cnt
            }

            let sql = 'INSERT INTO tb_user_hetong_shenpi SET ?'
            res = await mysqlUtil.execute(sql, [{
                uid,
                sta: 0,
                auditSta: 1,
                bianhao,
                mingcheng: params.mingcheng,
                qianyueriqi: params.qianyueriqi,
                wofangdanwei: params.wofangdanwei,
                wofangfuzeren: params.wofangfuzeren,
                duifangdanwei: params.duifangdanwei,
                duifangfuzeren: params.duifangfuzeren,
                isFawu: params.isFawu || '否',
                fawuYijian: params.fawuYijian,
                mingcheng: params.mingcheng,
                attaches: JSON.stringify(params.attaches || []),
                pics: JSON.stringify(params.pics || []),
                auditors: JSON.stringify(auditorsObj),
                createTime: Date.now()
            }])
            
            let applyId = res.insertId

            // 为审核人员添加任务
            await mysqlUtil.execute('INSERT INTO tb_user_task SET ?', [{
                uid: params.auditors[0].uid,
                typ: 15,
                relevenceId: applyId,
                pos: 0,
                title: '合同审批审批',
                content: name + '的合同审批需要您审批',
                sta: 0,
                createTime: Date.now()
            }])
            io.in(params.auditors[0].uid + '-app').emit('TASK-CHANGE')
            io.in(params.auditors[0].uid + '-app').emit('TASK-NEW')
            io.in(params.auditors[0].uid + '-web').emit('TASK-CHANGE')
            io.in(params.auditors[0].uid + '-web').emit('TASK-NEW')
            util.sendReminderSmsToUser(params.auditors[0].uid, '合同审批', '待审批')

            callback({code: 0, message: 'success'})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    revertHetongShenpi: async (io, socket, params, callback) => {
        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc
        if (!params.id) return callback({code: -1, message: '参数缺失'})

        try {
            let res = await mysqlUtil.execute('UPDATE tb_user_hetong_shenpi SET chexiao = 1 WHERE id = ? LIMIT 1', [params.id])
            if (res.affectedRows == 0) return ({code: -1, message: '撤销失败'})
            // 将审核人员的任务状态改下 并通知前端
            res = await mysqlUtil.execute('SELECT id, uid FROM tb_user_task WHERE typ = 15 AND relevenceId = ?', [params.id])
            for (let i = 0; i != res.length; i++) {
                await mysqlUtil.execute('UPDATE tb_user_task SET sta = 3 WHERE id = ? LIMIT 1', [res[i].id])
                // 通知前端
                io.in(res[i].uid + '-app').emit('TASK-REVERT', res[i].id)
                io.in(res[i].uid + '-web').emit('TASK-REVERT', res[i].id)
            }
            callback({code: 0, message: ''})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    hetongShenpiRecord: async(io, socket, params, callback) => {

        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        // 小于的id
        let lessThan = params.lessThan || 0
        // 大于的id
        let greaterThan = params.greaterThan || 0
        // 每页的数量
        let pageCount = params.pageCount || 10

        try {
            let sql = ''
            let sqlParams = []
            if (lessThan) {
                sql = 'SELECT * FROM tb_user_hetong_shenpi WHERE uid = ? AND id < ? ORDER BY id DESC LIMIT ?'
                sqlParams = [uid, lessThan, pageCount]
            } else if (greaterThan) {
                sql = 'SELECT * FROM tb_user_hetong_shenpi WHERE uid = ? AND id > ? ORDER BY id DESC LIMIT ?'
                sqlParams = [uid, greaterThan, pageCount]
            } else {
                sql = 'SELECT * FROM tb_user_hetong_shenpi WHERE uid = ? ORDER BY id DESC LIMIT ?'
                sqlParams = [uid, pageCount]
            }
            let res = await mysqlUtil.execute(sql, sqlParams)
            callback({code: 0, message: 'success', data: res})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    hetongShenpiRecordWeb: async(io, socket, params, callback) => {

        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        let pageIndex = parseInt(params.pageIndex || 1);
        let pageCount = parseInt(params.pageCount || 10);

        try {
            let res = await mysqlUtil.execute('SELECT COUNT(1) cnt FROM tb_user_hetong_shenpi WHERE uid = ?', [uid])
            let count = res[0].cnt
            let sql = 'SELECT * FROM tb_user_hetong_shenpi WHERE uid = ? ORDER BY id DESC LIMIT ?, ?'
            let params = [uid, (pageIndex - 1) * pageCount, pageCount]
            res = await mysqlUtil.execute(sql, params)
            callback({code: 0, message: 'success', data: {list: res, count}})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    hetongShenpiDetail: async(io, socket, params, callback) => {
        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        if (!params.id) return callback({code: -1, message: '参数错误'})

        try {
            let res = await mysqlUtil.execute('SELECT * FROM tb_user_hetong_shenpi WHERE id = ? LIMIT 1', [params.id])
            if (res.length == 0) return callback({code: -1, message: '不存在'})
            let applyInfo = res[0]
            applyInfo.auditors = applyInfo.auditors || []
            for (let key in applyInfo.auditors) {
                let sql = `
                    SELECT
                        con_position.name
                    FROM
                        tb_user
                    INNER JOIN con_position ON con_position.id = tb_user.position
                    WHERE tb_user.uid = ?
                    LIMIT 1
                `
                let r = await mysqlUtil.execute(sql, [applyInfo.auditors[key].uid])
                if (r.length > 0) {
                    applyInfo.auditors[key].positionName = r[0].name
                }
            }
            callback({code: 0, message: '', data: applyInfo})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 招标审核
    zhaobiaoShenhe: async (io, socket, params, callback) => {
        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        logger.debug('zhaobiao shenhe', params)

        if (!Array.isArray(params.attaches)) {
            return callback({code: -1, message: '参数错误'})
        }

        let auditorsObj = {}
        for (let i = 0; i != params.auditors.length; i++) {
            auditorsObj['auditor' + i] = { uid: params.auditors[i].uid, stepName: params.auditors[i].stepName, sta: 0 }
        }

        try {
            let res = await mysqlUtil.execute('SELECT name FROM tb_user WHERE uid = ? LIMIT 1', [uid])
            if (res.length == 0) return callback({code: -1, message: '玩家不存在'})
            let name = res[0].name

            // 编号自动生成 查询今年已经有多少申请了
            res = await mysqlUtil.execute('SELECT COUNT(1) cnt FROM tb_user_zhaobiao_shenhe WHERE createTime > ?', [moment().startOf('year').valueOf()])
            let year = new Date().getFullYear()
            let cnt = res[0].cnt
            let bianhao = ''
            if (cnt < 10) {
                bianhao = year + '00' + cnt
            } else if (cnt < 100) {
                bianhao = year  + '0' + cnt
            } else {
                bianhao = year + '' + cnt
            }

            let sql = 'INSERT INTO tb_user_zhaobiao_shenhe SET ?'
            res = await mysqlUtil.execute(sql, [{
                uid,
                sta: 0,
                auditSta: 1,
                bianhao,
                mingcheng: params.mingcheng,
                kongzhijia: params.kongzhijia,
                caigou: params.caigou,
                danwei: params.danwei,
                startDate: params.startDate,
                endDate: params.endDate,
                jiaofuDate: params.jiaofuDate,
                fuzeren: params.fuzeren,
                attaches: JSON.stringify(params.attaches || []),
                pics: JSON.stringify(params.pics || []),
                auditors: JSON.stringify(auditorsObj),
                createTime: Date.now()
            }])
            
            let applyId = res.insertId

            // 为审核人员添加任务
            await mysqlUtil.execute('INSERT INTO tb_user_task SET ?', [{
                uid: params.auditors[0].uid,
                typ: 16,
                relevenceId: applyId,
                pos: 0,
                title: '招标文件审核审批',
                content: name + '的招标文件审核需要您审批',
                sta: 0,
                createTime: Date.now()
            }])
            io.in(params.auditors[0].uid + '-app').emit('TASK-CHANGE')
            io.in(params.auditors[0].uid + '-app').emit('TASK-NEW')
            io.in(params.auditors[0].uid + '-web').emit('TASK-CHANGE')
            io.in(params.auditors[0].uid + '-web').emit('TASK-NEW')
            util.sendReminderSmsToUser(params.auditors[0].uid, '招标文件审核', '待审批')

            callback({code: 0, message: 'success'})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    revertZhaobiaoShenhe: async (io, socket, params, callback) => {
        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc
        if (!params.id) return callback({code: -1, message: '参数缺失'})

        try {
            let res = await mysqlUtil.execute('UPDATE tb_user_zhaobiao_shenhe SET chexiao = 1 WHERE id = ? LIMIT 1', [params.id])
            if (res.affectedRows == 0) return ({code: -1, message: '撤销失败'})
            // 将审核人员的任务状态改下 并通知前端
            res = await mysqlUtil.execute('SELECT id, uid FROM tb_user_task WHERE typ = 16 AND relevenceId = ?', [params.id])
            for (let i = 0; i != res.length; i++) {
                await mysqlUtil.execute('UPDATE tb_user_task SET sta = 3 WHERE id = ? LIMIT 1', [res[i].id])
                // 通知前端
                io.in(res[i].uid + '-app').emit('TASK-REVERT', res[i].id)
                io.in(res[i].uid + '-web').emit('TASK-REVERT', res[i].id)
            }
            callback({code: 0, message: ''})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    zhaobiaoShenheRecord: async(io, socket, params, callback) => {

        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        // 小于的id
        let lessThan = params.lessThan || 0
        // 大于的id
        let greaterThan = params.greaterThan || 0
        // 每页的数量
        let pageCount = params.pageCount || 10

        try {
            let sql = ''
            let sqlParams = []
            if (lessThan) {
                sql = 'SELECT * FROM tb_user_zhaobiao_shenhe WHERE uid = ? AND id < ? ORDER BY id DESC LIMIT ?'
                sqlParams = [uid, lessThan, pageCount]
            } else if (greaterThan) {
                sql = 'SELECT * FROM tb_user_zhaobiao_shenhe WHERE uid = ? AND id > ? ORDER BY id DESC LIMIT ?'
                sqlParams = [uid, greaterThan, pageCount]
            } else {
                sql = 'SELECT * FROM tb_user_zhaobiao_shenhe WHERE uid = ? ORDER BY id DESC LIMIT ?'
                sqlParams = [uid, pageCount]
            }
            let res = await mysqlUtil.execute(sql, sqlParams)
            callback({code: 0, message: 'success', data: res})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    zhaobiaoShenheRecordWeb: async(io, socket, params, callback) => {

        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        let pageIndex = parseInt(params.pageIndex || 1);
        let pageCount = parseInt(params.pageCount || 10);

        try {
            let res = await mysqlUtil.execute('SELECT COUNT(1) cnt FROM tb_user_zhaobiao_shenhe WHERE uid = ?', [uid])
            let count = res[0].cnt
            let sql = 'SELECT * FROM tb_user_zhaobiao_shenhe WHERE uid = ? ORDER BY id DESC LIMIT ?, ?'
            let params = [uid, (pageIndex - 1) * pageCount, pageCount]
            res = await mysqlUtil.execute(sql, params)
            callback({code: 0, message: 'success', data: {list: res, count}})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    zhaobiaoShenheDetail: async(io, socket, params, callback) => {
        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        if (!params.id) return callback({code: -1, message: '参数错误'})

        try {
            let res = await mysqlUtil.execute('SELECT * FROM tb_user_zhaobiao_shenhe WHERE id = ? LIMIT 1', [params.id])
            if (res.length == 0) return callback({code: -1, message: '不存在'})
            let applyInfo = res[0]
            applyInfo.auditors = applyInfo.auditors || []
            for (let key in applyInfo.auditors) {
                let sql = `
                    SELECT
                        con_position.name
                    FROM
                        tb_user
                    INNER JOIN con_position ON con_position.id = tb_user.position
                    WHERE tb_user.uid = ?
                    LIMIT 1
                `
                let r = await mysqlUtil.execute(sql, [applyInfo.auditors[key].uid])
                if (r.length > 0) {
                    applyInfo.auditors[key].positionName = r[0].name
                }
            }
            callback({code: 0, message: '', data: applyInfo})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    }
}